<?php

/**
 * Новость мультиязычная 
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfPropelFormTemplate.php 10377 2008-07-21 07:10:32Z dwhittle $
 */
class storyForm extends BaseMaterialForm
{
  public function configure()
  {
  	
  			unset( 
  		$this['created_at'],  
  		$this['updated_at'],  
  		$this['click'], 
  		$this['country'],
  		$this['custom_int3'],
  		$this['custom_text1'],
  		$this['custom_text2'],
  		$this['custom_text3'],
  		$this['custom_char2'],
  		$this['custom_char3'],
  		$this['seo_title'],
  		$this['seo_keyword'],
  		$this['stat'],
  		$this['parent_id'],
  		$this['link']);
  		
   		$c = new Criteria ( );	
		$c->addAnd ( FolderPeer::TREE_PARENT, 1, Criteria::NOT_EQUAL );
		$c->addAnd ( MaterialPeer::ID, 'tt' ); 		



          $this->setWidgets(array(
          'id'               => new sfWidgetFormInputHidden(array(),array('size'=>'60')),
          'type_id'           => new sfWidgetFormInputHidden(array(), array('value' =>'10', 'class'=>'test')),
          'title'               => new sfWidgetFormInput(array(),array('class'   =>  'material_title','style'=>'width:620px;')),
  	  'photo_path' => new inputImageTag (  array (), array('mat_id'=>$this->object->getId(),'folder'=>'news') ),
          'short_content' => new sfWidgetFormCKEditor (array('jsoptions'=>array('filebrowserBrowseUrl'=>sfConfig::get('app_ck_filebrouser'),
  	                                                                        'filebrowserUploadUrl' => sfConfig::get('app_ck_fileupload'),
                                                                                'toolbar ' => sfConfig::get('app_ck_toolbar'))) ),
  	  'content' => new sfWidgetFormCKEditor (array('jsoptions'=>array('filebrowserBrowseUrl'=>sfConfig::get('app_ck_filebrouser'),
  	                                                                  'filebrowserUploadUrl' => sfConfig::get('app_ck_fileupload'),
                                                                          'toolbar ' => sfConfig::get('app_ck_toolbar'))) ),
  	 'user_id' => new sfWidgetFormInputHidden (  array (), array ('value' => sfContext::getInstance()->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ))),
  	 
    ));

                    /////Статус ссылки
		 if(sfContext::getInstance()->getUser()->isSuperAdmin())
		 {
		 	$this->widgetSchema['pub'] = new sfWidgetFormInputCheckbox();
		 }
		 ////


		$this->widgetSchema->setLabels ( array (
                'title' =>         'Наименование',
		'photo_path'    => 'Фото',
  		'short_content' => 'Краткое содержание',
                'pub'    =>        'Опубликован',
  		'content'    =>    'Содержание'
                                                       ));
  		

		$this->validatorSchema ['photo_path'] = new sfValidatorFile ( array ('required' => false, 
		'path' => sfConfig::get ( 'sf_web_dir' ) . '/uploads/material/news', 
		'mime_types' => 'web_images', 'max_size' => 500000, // 360 kB
                'validated_file_class' => 'sfMatNewsValidatedFile'
         ) );
        
  	

        $custom_decorator = new sfWidgetFormSchemaFormatterDefList($this->getWidgetSchema());
        $this->getWidgetSchema()->addFormFormatter('deflist', $custom_decorator);
        $this->getWidgetSchema()->setFormFormatterName('deflist');
       
        $this->validatorSchema->setOption('allow_extra_fields', true);    
  		 
        $this->widgetSchema->setNameFormat('material[%s]');
  		 
        //$this->embedI18n(sfContext::getInstance()->getUser()->getLangs());
            
        
            
            
  
  }
  
  
  
  	public function saveMat2FolderList($con = null) {
		if (! $this->isValid ()) {
			throw $this->getErrorSchema ();
		}
		
		if (! isset ( $this->widgetSchema ['mat2_folder_list'] )) {
			// somebody has unset this widget
			return;
		}
		
		if (is_null ( $con )) {
			$con = $this->getConnection ();
		}
		
		$c = new Criteria ( );
		$c->add ( Mat2FolderPeer::MATERIAL_ID, $this->object->getPrimaryKey () );
		Mat2FolderPeer::doDelete ( $c, $con );
		
		$values = $this->getValue ( 'mat2_folder_list' );
		if (is_array ( $values )) {
			
			foreach ( $values as $value ) {
				$obj = new Mat2Folder ( );
				$obj->setMaterialId ( $this->object->getPrimaryKey () );
				$obj->setFolderId ( $value );
				$obj->save ();
				
				$f = FolderPeer::retrieveByPK ( $value );
				
				////Добавляем счетчик
				FolderPeer::recount ( $f );
				
				if ($f->hasParent ()) {
					$par = $f->retrieveParent ();
					
					if (! in_array ( $par->getId (), $values )) {
						
						$this->saverec ( $par, $this->object->getPrimaryKey () );
						////Добавляем счетчик
						if ($par->hasParent ()) {
							$parr = $par->retrieveParent ();
							
							if (! in_array ( $parr->getId (), $values )) {
								//print_r($values).'-'.$parr->getId();
						         ////Добавляем счетчик
				                
								$this->saverec ( $parr, $this->object->getPrimaryKey () );
								if ($parr->hasParent ()) {
									$parrr = $parr->retrieveParent ();
									if (! in_array ( $parrr->getId (), $values )) {
										$this->saverec ( $parrr, $this->object->getPrimaryKey () );
						                ////Добавляем счетчик
				                       								
									}
								}
							
							}
						
						}
					}
				
				}
			
			}
		}
	}
	
	public function saverec($par, $mat_id) {
		
		//echo $par->getId().'-'.$mat_id;
		$c = new Criteria ( );
		$c->add ( Mat2FolderPeer::FOLDER_ID, $par->getId () );
		$c->addAnd ( Mat2FolderPeer::MATERIAL_ID, $mat_id );
		$cnt = Mat2FolderPeer::doCount ( $c );
		if ($cnt == 0) {
			$re = new Mat2Folder ( );
			$re->setMaterialId ( $mat_id );
			$re->setFolderId ( $par->getId () );
			$re->save ();
		}
	
	}
 
  
 function myFormatter($widget, $inputs)
  {
    $str = '<b>Раздел</b>'.get_partial('checked_folders',array('arr'=>$this['mat2_folder_list']->getValue(),'form'=>$this,'scope_id'=>sfConfig::get('app_scope_adv'))).get_component('zdFolder','show_folders',array('arr'=>$this['mat2_folder_list']->getValue(),'folder_id'=>sfConfig::get('app_folder_adv'),'width_check'=>'yes'));
    //$str .= '<b>Регионы</b>'.get_partial('checked_folders',array('form'=>$this,'scope_id'=>sfConfig::get('app_scope_region'))).get_component('zdFolder','show_folders',array('folder_id'=>sfConfig::get('app_folder_region'),'width_check'=>'yes'));
    return $str;
  }
   
}

class sfWidgetFormSchemaFormatterDefList extends sfWidgetFormSchemaFormatter {
    protected
      $rowFormat                 = '<div class="sf_admin_form_row">%label%%error%%field%%help%%hidden_fields%</div>',
      $helpFormat                = '<span class="help">%help%</span>',
      $errorRowFormat            = '<dt class="error">Errors:</dt><dd>%errors%</dd>',
      $errorListFormatInARow     = '<ul class="error_list">%errors%</ul>',
      $errorRowFormatInARow      = '<li>%error%</li>',
      $namedErrorRowFormatInARow = '<li>%name%: %error%</li>',
      $decoratorFormat           = '<dl id="formContainer">%content%</dl>';
}